package com.springvision.yuanfeng.core.tcp;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.springvision.yuanfeng.core.GprsProtocol;
import com.springvision.yuanfeng.device.entity.Device;
import com.springvision.yuanfeng.device.entity.DeviceMessage;
import com.springvision.yuanfeng.device.service.DeviceMessageService;
import com.springvision.yuanfeng.device.service.DeviceService;
import com.springvision.yuanfeng.device.service.DeviceStatService;
import com.springvision.yuanfeng.locale.entity.DevStation;
import com.springvision.yuanfeng.locale.service.DevStationService;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.ChannelHandler.Sharable;;

@SuppressWarnings("serial")
@Service
@Qualifier("serverChannelHandler")
@Lazy(false)
@Sharable
public class YfCloudServerHandler extends SimpleChannelInboundHandler<String> implements Serializable {

	private static Logger logger = Logger.getLogger(YfCloudServerHandler.class);

	@Autowired
	private DevStationService devStationService;

	@Autowired
	private DeviceService deviceService;

	@Autowired
	private DeviceMessageService deviceMessageService;

	@Autowired
	private DeviceStatService deviceStatService;

	// @Autowired
	// private YfTCPClient yfTCPClient;

	// private int counter;

	Boolean active = false;

	// 读取客户端发送的数据
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		// int i = ++counter;
		System.err.println("raw msg ====================>[" + msg + "]");
		// System.err.println("raw msg ======" + i + "==============>[" + msg +
		// "]");

		// yfTCPClient.send("---" + i + "=====>" + msg + "|");

		msg = StringUtils.replaceIgnoreCase(msg, "yuanfeng", "");
		msg = StringUtils.replace(msg, "$", "");
		// System.out.println("---入库 msg----" + msg);
		save(msg);
		ctx.channel().writeAndFlush("server is dad!");
	}

	// 新客户端接入
	@Override
	public void channelActive(final ChannelHandlerContext ctx) throws Exception {
		System.err.println("channelActive---server");
	}

	// 客户端断开
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.err.println("channelInactive---server");
		active = false;
	}

	// 异常
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.err.println("exceptionCaught!" + cause);
		// 关闭通道
		ctx.channel().close();
		// 打印异常
		cause.printStackTrace();
	}

	// @Override
	// public void channelReadComplete(ChannelHandlerContext ctx) throws
	// Exception {
	//
	// System.out.println("channel 通道 Read 读取 Complete 完成");
	// ctx.flush();
	// }

	public void save(String msg) {
		GprsProtocol protocol = new GprsProtocol(msg);

		DevStation newDevStation = protocol.getDevStation();
		DevStation oldDevStation = devStationService.getByName(newDevStation);

		// logger.error("库中是否存在场站 ：" + oldDevStation);
		// System.err.println("库中是否存在场站 ：" + oldDevStation);

		if (oldDevStation == null) {
			devStationService.save(newDevStation);
		} else {
			newDevStation = oldDevStation;
		}
		// logger.error("保存场站后是否返回场站id：" + newDevStation.getId());
		// System.err.println("保存场站后是否返回场站id：" + newDevStation.getId());

		List<DeviceMessage> devMsgList = protocol.getDeviceMessageList();

		// System.out.println("insert station id ---is---" +
		// newDevStation.getId());
		if (CollectionUtils.isNotEmpty(devMsgList)) {
			for (DeviceMessage deviceMessage : devMsgList) {
				/**
				 * 1.device表里查询是否存在 这个 stationId的deviceCode 对应的device
				 * 如果不存在：写入设备表，并获取到id 2.获取这个设备的当前小时的最大上报次数
				 * 判断是否为第一次上报，第一次上报写库其他抛弃
				 */
				// System.out.println("deviceMessage time ---" +
				// deviceMessage.getCreateDate());

				Device device = deviceService.findDeviceCodeByStaDev(newDevStation.getId(),
						deviceMessage.getDeviceCode());

				if (device == null) {
					Device reportDevice = deviceMessage.getDevice();
					reportDevice.setDevStation(newDevStation);
					deviceService.saveOnline(reportDevice);
					device = reportDevice;
				}

				// System.out.println("device outer id---" + device.getId());

				Integer num = deviceStatService.getDeviceReportCount(device.getId());

				// System.out.println("num--is------" + num);
				if (num.equals(0)) {
					System.out.println("inside device id---" + device.getId());
					deviceMessage.setDeviceId(device.getId());
					deviceMessageService.save(deviceMessage);

				}

			}
		}

	}
}